using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Web;
using Sedna.Core.Common;
using Sedna.Core.Common.Objects.Navigation;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using Sedna.Core.Support;
using Sedna.DAO;

namespace Sedna.Core.Controls.Actions
{
    public class LoadEntityFromGridAction: AbstractAction
    {
        protected String objectNotFoundStatus = "NotFound";
        
        private String pageDataPath;
        private String indexRequestVar = "index";
        private String objectContextLocationPath;
        private IBaseDAO objectDAO;

        # region Properties

        public string PageDataPath
        {
            get { return pageDataPath; }
            set { pageDataPath = value; }
        }

        public string IndexRequestVar
        {
            set { indexRequestVar = value; }
        }

        protected object GetObject()
        {
            return scopePathParser.Parse(ObjectContextLocationPath).Value;
        }

        public IBaseDAO ObjectDAO
        {
            set { objectDAO = value; }
        }

        public string ObjectContextLocationPath
        {
            get { return objectContextLocationPath; }
            set { objectContextLocationPath = value; }
        }
        
        public String ObejctNotFoundStatus
        {
            set { objectNotFoundStatus = value; }
        }

        # endregion

        public override IActionResult Execute(IExecutionContext executionContext)
        {
            IList pageData = executionContext.GetPropertyValue(pageDataPath) as IList;
            
            string strIndex = (string)executionContext.GetScopedValue(indexRequestVar, Scope.Request);
            
            Object obj = null;
            
            if (pageData != null &&  !String.IsNullOrEmpty(strIndex) && !"null".Equals(strIndex.ToLower()))
            {
                obj = pageData[Int32.Parse(strIndex, CultureInfo.InvariantCulture)];
                
                if (objectDAO != null)
                {
                    objectDAO.AttachToSession(obj);
                }                
            }

            scopePathParser.Parse(ObjectContextLocationPath).Value = obj;

            return (obj != null) ? CreateResult(successStatus) : CreateResult(objectNotFoundStatus);
        }
    }
}
